import {
  Button,
  DatePicker,
  Form,
  Image,
  Input,
  message,
  Select,
  Table,
  Tag,
  Tooltip,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { PlusIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { apiChannelAll, apiNovelList, apiNovelTagAll } from "~/api";
import Filter from "~/components/ui/filter";
import Title from "~/components/ui/title";
import { useDictMap } from "~/contexts/dict";
import { useTableHeight } from "~/hooks/useTableHeight";
import type { IPageData } from "~/types/common";
import type { IChannel } from "~/types/manage/channel/list";
import type { IFilter, INovel } from "~/types/manage/content/novel";
import NovelChannelAuthDrawer from "./manage/content/novel/novel-channel-auth-drawer";
import NovelChapterModal from "./manage/content/novel/novel-chapter-modal";
import NovelModal from "./manage/content/novel/novel-modal";

export default function Page() {
  const [filterForm] = Form.useForm<IFilter>();
  const [dataList, setDataList] = useState<IPageData<INovel> | null>(null);
  const [loading, setLoading] = useState(false);
  const tableHeight = useTableHeight(443);

  const [modalVisible, setModalVisible] = useState(false);
  const [editNovel, setEditNovel] = useState<INovel | null>(null);
  const [tagMap, setTagMap] = useState<Record<number, string>>({});

  const [chapterModalVisible, setChapterModalVisible] = useState(false);

  const [channelAuthDrawerVisible, setChannelAuthDrawerVisible] =
    useState(false);
  const [channelAuthDrawerNovel, setChannelAuthDrawerNovel] =
    useState<INovel | null>(null);

  const [channelList, setChannelList] = useState<IChannel[]>([]);

  const dictMap = useDictMap();

  const _handler = {
    addNovel: () => {
      setModalVisible(true);
      setEditNovel(null);
    },
    editNovel: (novel: INovel) => {
      setModalVisible(true);
      setEditNovel(novel);
    },
    editNovelChapter: (novel: INovel) => {
      setChapterModalVisible(true);
      setEditNovel(novel);
    },
    novelChannelAuth: (novel: INovel) => {
      setChannelAuthDrawerVisible(true);
      setChannelAuthDrawerNovel(novel);
    },
  };

  const _fetch = {
    novelTagAll: async () => {
      const resp = await apiNovelTagAll();
      setTagMap(
        resp.reduce(
          (prev, cur) => ({ ...prev, [cur.id]: cur.label }),
          {} as Record<number, string>,
        ),
      );
    },
    novelList: async (filter: IFilter) => {
      try {
        const resp = await apiNovelList(filter);
        setDataList(resp);
      } catch (error: any) {
        message.error({
          content: error.message,
        });
      }
    },
    channelList: async () => {
      const resp = await apiChannelAll();
      setChannelList(resp);
    },
  };

  const _ui: {
    tableColumns: ColumnsType<INovel>;
  } = {
    tableColumns: [
      {
        title: (
          <div className="flex flex-col">
            <span>编号</span>
            <span>原编号</span>
          </div>
        ),
        dataIndex: "serialNo",
        key: "serialNo",
        width: 120,
        fixed: "left",
        render: (_, record) => {
          return (
            <div className="flex flex-col">
              <div>
                <Tooltip title="编辑内容基本信息">
                  <a onClick={() => _handler.editNovel(record)}>
                    {record.serialNo}
                  </a>
                </Tooltip>
              </div>
              <div>{record.originSerialNo || "--"}</div>
              <div className="flex justify-around">
                <div>
                  <Tag color="green">{dictMap[record.source]?.label}</Tag>
                </div>
                <div>
                  <Tag>爆</Tag>
                </div>
                <div>
                  <Tag>重</Tag>
                </div>
              </div>
            </div>
          );
        },
      },
      {
        title: "封面",
        dataIndex: "cover",
        key: "cover",
        fixed: "left",
        width: 80,
        render: (cover) => {
          return (
            <Image
              preview={false}
              width={60}
              height={80}
              src={cover}
              fallback=""
            />
          );
        },
      },

      {
        title: (
          <div className="flex flex-col">
            <span>标题</span>
            <span>作者</span>
          </div>
        ),
        dataIndex: "title",
        key: "title",
        fixed: "left",
        width: 220,
        render: (_, record) => {
          return (
            <div className="flex flex-col gap-2">
              <div>
                <Tag>{dictMap[record.status]?.label}</Tag>
                <span>{record.title}</span>
              </div>
              <div>
                <span>作者: </span>
                {record.penName || "--"}（{record.realName || "--"}）
              </div>
            </div>
          );
        },
      },
      {
        title: (
          <div className="flex flex-col">
            <span>男女频</span>
            <span>作品类型</span>
          </div>
        ),
        dataIndex: "kind",
        key: "authors",
        width: 160,
        render: (_, record) => {
          return (
            <div className="grid grid-cols-3 gap-2">
              <div>{dictMap[record.kind]?.label}</div>
              <div>{dictMap[record.lengthType]?.label}</div>
              <div>{dictMap[record.contentType]?.label}</div>
              <div className="col-span-2">
                {dictMap[record.visualAngle]?.label}
              </div>
            </div>
          );
        },
      },
      {
        title: "作品标签",
        dataIndex: "tags",
        key: "tags",
        width: 80,
        render: (_, record) => {
          return (
            <div className="flex flex-col gap-2">
              {record.tags?.map((item, index) => {
                return (
                  <div key={index}>
                    <Tag key={item}>{tagMap[item]}</Tag>
                  </div>
                );
              })}
            </div>
          );
        },
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark",
        width: 220,
      },
      {
        title: "简介",
        dataIndex: "desc",
        key: "desc",
        width: 320,
        render: (value) => {
          return <p className="line-clamp-3">{value}</p>;
        },
      },
      {
        title: (
          <div className="flex flex-col">
            <span>收费字数/总字数</span>
            <span>收费章节/总章节</span>
          </div>
        ),
        dataIndex: "desc",
        key: "desc",
        width: 160,
        render: (_, record) => {
          return (
            <div className="flex flex-col gap-2">
              <div>
                {record.chargeWords} / {record.totalWords}
              </div>
              <div>
                {record.chargeChapters} / {record.totalChapters}
              </div>
            </div>
          );
        },
      },
      {
        title: "渠道",
        children: channelList
          .filter((channelItem) => channelItem.type === "CHANNEL_TYPE_推文")
          .map((channelItem) => {
            return {
              title: channelItem.name,
              dataIndex: channelItem.id,
              key: channelItem.id,
              width: 120,
              render: (_, record) => {
                const auth = record.channelAuthList?.find(
                  (authItem) => authItem.channelId === channelItem.id,
                );
                return auth ? (
                  <div className="flex flex-col gap-2 text-green-400">
                    <span>{dictMap[auth.authType]?.label}</span>
                    <span>{dictMap[auth.authStatus]?.label}</span>
                  </div>
                ) : (
                  <div className="flex flex-col gap-2 text-gray-300">
                    <span>未授权</span>
                  </div>
                );
              },
            };
          }),
      },
      {
        title: "操作",
        dataIndex: "action",
        key: "action",
        width: 80,
        fixed: "right",
        render: (_, record) => {
          return (
            <div className="flex flex-col gap-2">
              <Button
                size="small"
                type="link"
                onClick={() => {
                  _handler.editNovelChapter(record);
                }}
              >
                编辑章节
              </Button>
              <Button
                size="small"
                type="link"
                onClick={() => {
                  _handler.novelChannelAuth(record);
                }}
              >
                渠道授权
              </Button>
            </div>
          );
        },
      },
    ],
  };

  useEffect(() => {
    _fetch.novelList(filterForm.getFieldsValue(true));
    _fetch.novelTagAll();
    _fetch.channelList();
  }, []);

  return (
    <>
      <div className="flex h-full flex-col gap-4">
        <Title
          title="文章管理"
          buttonGroups={[
            <Button
              type="primary"
              onClick={() => {
                _handler.addNovel();
              }}
            >
              <PlusIcon size={18} />
              新增文章
            </Button>,
          ]}
        />
        <Filter
          form={filterForm}
          initialValues={{
            pageNum: 1,
            pageSize: 100,
          }}
          onSearch={() => {
            _fetch.novelList(filterForm.getFieldsValue(true));
          }}
          onReset={() => {
            _fetch.novelList(filterForm.getFieldsValue(true));
          }}
        >
          <Form.Item label={"用户"} name={"userId"}>
            <Select />
          </Form.Item>
          <Form.Item label={"笔名"} name={"userAuthorId"}>
            <Select />
          </Form.Item>

          <Form.Item label={"编号"} name={"serialNo"}>
            <Input />
          </Form.Item>
          <Form.Item label={"原编号"} name={"originSerialNo"}>
            <Input />
          </Form.Item>
          <Form.Item label={"标题"} name={"title"}>
            <Input />
          </Form.Item>
          <Form.Item label={"来源"} name={"source"}>
            <Select />
          </Form.Item>
          <Form.Item label={"合同状态"} name={"contractStatus"}>
            <Select />
          </Form.Item>
          <Form.Item label={"男女频"} name={"kind"}>
            <Select />
          </Form.Item>
          <Form.Item label={"长短篇"} name={"type"}>
            <Select />
          </Form.Item>
          <Form.Item label={"视角"} name={"visualAngle"}>
            <Select />
          </Form.Item>
          <div className="flex justify-between gap-2">
            <Form.Item label={"爆款"} name={"isBomb"}>
              <Select
                options={[
                  {
                    label: "全部",
                    value: "",
                  },
                  {
                    label: "是",
                    value: true,
                  },
                  {
                    label: "否",
                    value: false,
                  },
                ]}
              />
            </Form.Item>
            <Form.Item label={"重点"} name={"isFocus"}>
              <Select
                options={[
                  {
                    label: "全部",
                    value: "",
                  },
                  {
                    label: "是",
                    value: true,
                  },
                  {
                    label: "否",
                    value: false,
                  },
                ]}
              />
            </Form.Item>
          </div>

          <Form.Item label={"字数区间"} name={"wordsRange"}>
            <Input />
          </Form.Item>
          <Form.Item label={"价格区间"} name={"priceRange"}>
            <Input />
          </Form.Item>
          <Form.Item label={"入库时间"} name={"storageTimeRange"}>
            <DatePicker />
          </Form.Item>
          <Form.Item label={"状态"} name={"status"}>
            <Select />
          </Form.Item>
        </Filter>
        <div className="flex-1 overflow-hidden">
          <div className="h-full w-full">
            <Table
              bordered
              size="small"
              scroll={{
                y: tableHeight,
                x: "max-content",
              }}
              rowKey={(record) => record.id}
              columns={_ui.tableColumns}
              dataSource={dataList?.list}
              locale={{
                emptyText: "暂无数据",
              }}
              pagination={{
                showTotal: (total, range) => {
                  return `共 ${total} 条`;
                },
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 100,
                showSizeChanger: true,
                onChange(page, pageSize) {
                  filterForm.setFieldsValue({
                    pageNum: page,
                    pageSize: pageSize,
                  });
                  _fetch.novelList(filterForm.getFieldsValue(true));
                },
                pageSize: dataList?.pageSize,
                current: dataList?.pageNum,
                total: dataList?.total,
              }}
            />
          </div>
        </div>
      </div>
      <NovelModal
        visible={modalVisible}
        record={editNovel}
        onCancel={() => {
          setModalVisible(false);
          setEditNovel(null);
        }}
        onOk={() => {
          setModalVisible(false);
          _fetch.novelList(filterForm.getFieldsValue(true));
        }}
      />
      <NovelChapterModal
        visible={chapterModalVisible}
        novelRecord={editNovel}
        onCancel={() => {
          setChapterModalVisible(false);
          setEditNovel(null);
        }}
        onOk={() => {
          setChapterModalVisible(false);
          _fetch.novelList(filterForm.getFieldsValue(true));
        }}
      />
      <NovelChannelAuthDrawer
        visible={channelAuthDrawerVisible}
        novel={channelAuthDrawerNovel}
        onClose={() => {
          setChannelAuthDrawerNovel(null);
          setChannelAuthDrawerVisible(false);
        }}
        onOk={() => {
          setChannelAuthDrawerNovel(null);
          setChannelAuthDrawerVisible(false);
          _fetch.novelList(filterForm.getFieldsValue(true));
        }}
      />
    </>
  );
}
